import { Component, OnInit } from '@angular/core';
import { CanDraw } from '../../common/draw/draw.component';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized } from '@angular/router';
import { CloudMachineService } from '../../common/cloudMachine.service';
import { EsCommonService } from '../../common/escommon.service';
import { PsMachineService } from '../../common/PsMachine.service';

@Component({
  templateUrl: './psMachine.detail.html',
  styleUrls: ['./psMachine.detail.css', '../../app.component.css']
})
export class PsMachineDetailComponent implements CanDraw, OnInit {
  data: any;
  detail: any = {};
  equipmentData: any;
  equipmentType: any;
  // 磁盘信息列表
  diskHeaders = [
    {
      field: 'name',
      title: '磁盘',
      width: '50%',
    },
    {
      field: 'rate',
      title: '磁盘使用率',
      width: '25%',
    },
    {
      field: 'space',
      title: '可用磁盘空间',
      width: '25%',
    }
  ];
  diskDatas = [
    {
      name: '/dev/sda1',
      rate: '74%',
      space: '74GB',
    },
    {
      name: 'tmpfs(/dev/shm)',
      rate: '100%',
      space: '0GB',
    }
  ];
  // 租户资源列表
  tenantHeaders = [
    {
      field: 'name',
      title: '名称',
      canSort: false,
      width: '15%',
    },
    {
      field: 'ip',
      title: 'IP',
      canSort: true,
      width: '15%',
    },
    {
      field: 'cpu',
      title: 'cpu',
      canSort: true,
      width: '10%',
    },
    {
      field: 'memory',
      title: '内存',
      canSort: true,
      width: '15%',
    },
    {
      field: 'network',
      title: '网卡流量状态',
      canSort: true,
      width: '10%',
    },
    {
      field: 'disk',
      title: '文件系统使用状况',
      canSort: true,
      width: '15%',
    },
    {
      field: 'os',
      title: '操作系统型号',
      canSort: true,
      width: '10%',
    },
    {
      field: 'warn',
      title: '今日告警',
      canSort: true,
      width: '10%',
    },
  ];
  tenantCloudDatas: any;
  // 翻页
  totalCount: number;
  nowPage: number = 1;
  pageSize: number = 6;
  // 图表配置
  ping: any = {
    echartsIntance: null,
    echartOption: {
      backgroundColor: '#fff',
      title: {
        left: '20px',
        top: '15px',
        text: '服务器连通性 网卡流量',
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      grid: {
        left: '25px',
        right: '35px',
        top: '65px',
        bottom: '25px',
        containLabel: true
      },
      legend: {
        show: true,
        top: '25px',
        right: '35px',
        data: ['Ping']
      },
      xAxis: {
        type: 'category',
        data: [],
        boundaryGap: false,
        splitLine: {
          show: true,
          interval: 'auto',
          lineStyle: {
            color: ['#e2e2e2']
          }
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#999999'
          }
        },
        axisLabel: {
          margin: 10,
          textStyle: {
            fontSize: 12,
            color: '#666666'
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: true,
          interval: 'auto',
          lineStyle: {
            color: ['#e2e2e2']
          }
        },
        axisLabel: {
          formatter: '{value}\n'
        }
      },
      series: [
        {
          name: 'Ping',
          type: 'line',
          smooth: true,
          sampling: 'average',
          itemStyle: {
            normal: {
              color: '#3abea4'
            }
          },
          areaStyle: {
            normal: {
              color: { "x": 0, "y": 0, "x2": 0, "y2": 1, "type": "linear", "global": false, "colorStops": [{ "offset": 0, "color": "#bce9e1" }, { "offset": 0.5, "color": "#c8eee9" }, { "offset": 1, "color": "#e1f6f8" }] }
            }
          },
          data: [40, 50, 60, 70, 80, 90, 80]
        }
      ]
    }
  };
  cpu: any = {
    echartsIntance: null,
    echartOption: {
      backgroundColor: '#fff',
      title: {
        left: '20px',
        top: '15px',
        text: 'CPU使用率',
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      grid: {
        left: '25px',
        right: '35px',
        top: '65px',
        bottom: '25px',
        containLabel: true
      },
      legend: {
        show: true,
        top: '25px',
        right: '35px',
        data: ['CPU']
      },
      xAxis: {
        type: 'category',
        data: [],
        boundaryGap: false,
        splitLine: {
          show: true,
          interval: 'auto',
          lineStyle: {
            color: ['#e2e2e2']
          }
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#999999'
          }
        },
        axisLabel: {
          margin: 10,
          textStyle: {
            fontSize: 12,
            color: '#666666'
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: true,
          interval: 'auto',
          lineStyle: {
            color: ['#e2e2e2']
          }
        },
        axisLabel: {
          formatter: '{value}\n'
        }
      },
      series: [
        {
          name: 'CPU',
          type: 'line',
          smooth: true,
          sampling: 'average',
          itemStyle: {
            normal: {
              color: '#3abea4'
            }
          },
          areaStyle: {
            normal: {
              color: { "x": 0, "y": 0, "x2": 0, "y2": 1, "type": "linear", "global": false, "colorStops": [{ "offset": 0, "color": "#bce9e1" }, { "offset": 0.5, "color": "#c8eee9" }, { "offset": 1, "color": "#e1f6f8" }] }
            }
          },
          data: [40, 50, 60, 70, 80, 90, 80]
        }
      ]
    }
  };
  memory: any = {
    echartsIntance: null,
    echartOption: {
      backgroundColor: '#fff',
      title: {
        left: '20px',
        top: '15px',
        text: '内存使用率',
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      grid: {
        left: '25px',
        right: '35px',
        top: '65px',
        bottom: '25px',
        containLabel: true
      },
      legend: {
        show: true,
        top: '25px',
        right: '35px',
        data: ['物理内存']
      },
      xAxis: {
        type: 'category',
        data: [],
        boundaryGap: false,
        splitLine: {
          show: true,
          interval: 'auto',
          lineStyle: {
            color: ['#e2e2e2']
          }
        },
        axisTick: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: '#999999'
          }
        },
        axisLabel: {
          margin: 10,
          textStyle: {
            fontSize: 12,
            color: '#666666'
          }
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: true,
          interval: 'auto',
          lineStyle: {
            color: ['#e2e2e2']
          }
        },
        axisLabel: {
          formatter: '{value}\n'
        }
      },
      series: [
        {
          name: '物理内存',
          type: 'line',
          smooth: true,
          sampling: 'average',
          itemStyle: {
            normal: {
              color: '#3abea4'
            }
          },
          areaStyle: {
            normal: {
              color: { "x": 0, "y": 0, "x2": 0, "y2": 1, "type": "linear", "global": false, "colorStops": [{ "offset": 0, "color": "#bce9e1" }, { "offset": 0.5, "color": "#c8eee9" }, { "offset": 1, "color": "#e1f6f8" }] }
            }
          },
          data: [40, 50, 60, 70, 80, 90, 80]
        }
      ]
    }
  };
  pie: any = {
    echartsIntance: null,
    echartOption: {
      backgroundColor: '#fff',
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      color: [],
      legend: {
        orient: 'vertical',
        x: 'center',
        y: 'bottom',
        data: []
      },
      title: {
        show: true,
        text: '',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontFamily: 'impact',
          fontSize: 45
        }
      },
      series: [
        {
          name: '',
          type: 'pie',
          radius: ['45%', '70%'],
          avoidLabelOverlap: false,
          label: {
            normal: { show: false },
            emphasis: { show: false }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          data: []
        }
      ]
    }
  };
  pingChangeData: any;
  cpuChangeData: any;
  memoryChangeData: any;
  pieChangeData: any;
  currentTab: any;
  legend = {
    cpu: {
      name: '计算资源',
      color: '#a3e1d4'
    },
    network: {
      name: '网络资源',
      color: '#9cc3da'
    },
    disk: {
      name: '存储资源',
      color: '#b5b8cf'
    },
  }
  legendKeys = Object.keys(this.legend);

  constructor(
    private router: Router,
    private psMachineService: PsMachineService,
    private esCommonService: EsCommonService,
    private cloudMachineService: CloudMachineService) {
  }

  ngOnInit(): void {    
    this.equipmentType = this.data.type;
    this.detail = this.psMachineService.getDetail(this.data.data.name);
    let hour = this.esCommonService.getFormatDate(new Date(), 'h');
    let list = [];
    for (let i = 6; i >= 0; i--) {
      let time = hour > i ? hour - i : hour + 24 - i;
      list.push(time.toString() + ':00');
    }
    this.ping.echartOption.series.data = [];
    this.cpu.echartOption.series.data = [];
    this.memory.echartOption.series.data = [];
    for (let i = 0; i < 7; i++) {
      this.ping.echartOption.series.data.push(Math.ceil(Math.random() * 300));
      this.cpu.echartOption.series.data.push(Math.ceil(Math.random() * 100));
      this.memory.echartOption.series.data.push(Math.ceil(Math.random() * 1000));
    }
    this.pingChangeData = {
      xAxis: {
        data: list
      },
      series: [{
        data: this.ping.echartOption.series.data
      }]
    };
    this.cpuChangeData = {
      title: {
        left: '20px',
        top: '10px',
        text: 'CPU使用率',
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      grid: {
        left: '10px',
        right: '15px',
        top: '45px',
        bottom: '10px'
      },
      legend: {
        show: true,
        top: '10px',
        right: '15px',
        data: ['CPU']
      },
      xAxis: {
        data: list
      },
      series: [{
        data: this.cpu.echartOption.series.data
      }]
    };
    this.memoryChangeData = {
      title: {
        left: '20px',
        top: '10px',
        text: '内存使用率',
        textStyle: {
          color: '#333',
          fontSize: 14
        }
      },
      grid: {
        left: '10px',
        right: '15px',
        top: '45px',
        bottom: '10px'
      },
      legend: {
        show: true,
        top: '10px',
        right: '15px',
        data: ['物理内存']
      },
      xAxis: {
        data: list
      },
      series: [{
        data: this.memory.echartOption.series.data
      }]
    };
    switch (this.equipmentType) {
      case 'machine':
        this.equipmentData = [
          {
            header: 'IP',
            value: this.data.data.name || '-'
          },
          {
            header: 'SN',
            value: this.data.data.sn || '-'
          },
          {
            header: '状态',
            value: this.getStatus() || '-'
          },
          {
            header: '芯片标准',
            value: this.data.data.standard || this.detail.standard || '-'
          },
          {
            header: 'CPU配置',
            value: this.data.data.cpu || this.detail.cpu || '-'
          },
          {
            header: '内存配置',
            value: this.data.data.memory || this.detail.memory || '-'
          },
          {
            header: '机柜',
            value: this.data.data.cabinet || '-'
          },
          {
            header: '用途',
            value: '-'
          },
          {
            header: '服务器品牌',
            value: this.data.data.brand || this.detail.brand || '-'
          },
          {
            header: '服务器提供商',
            value: this.data.data.provider || this.detail.provider || '-'
          },
          {
            header: '服务开始时间',
            value: this.getDate(this.data.data.startTime) || '-'
          },
          {
            header: '服务结束时间',
            value: this.getDate(this.data.data.endTime) || '-'
          }
        ];
        break;
      case 'cloud':
        this.equipmentData = [
          {
            header: 'IP',
            value: this.data.data.ip || '-'
          },
          {
            header: '内存配置',
            value: this.data.data.memory || this.detail.memory || '-'
          },
          {
            header: '端口号',
            value: '-'
          },
          {
            header: '登录名',
            value: '-'
          },
          {
            header: 'CPU配置',
            value: this.data.data.cpu || this.detail.cpu || '-'
          },
          {
            header: '备注',
            value: this.data.data.comment || '-'
          },
          {
            header: 'OS',
            value: this.data.data.os || '-'
          }
        ];
        break;
      case 'tenants':
        this.loadData({
          search: '',
          pageNo: this.nowPage,
          pageSize: this.pageSize,
        });
        this.switchTab('cpu');
        this.pingChangeData = {
          title: {
            left: '10px',
            top: '10px',
            text: '计算资源',
            textStyle: {
              color: '#333',
              fontSize: 14
            }
          },
          grid: {
            left: '10px',
            right: '20px',
            top: '40px',
            bottom: '10px'
          },
          legend: {
            show: false
          },
          xAxis: {
            data: list
          },
          series: [{
            data: this.ping.echartOption.series.data
          }]
        };
        this.cpuChangeData = {
          title: {
            left: '10px',
            top: '10px',
            text: '网络资源',
            textStyle: {
              color: '#333',
              fontSize: 14
            }
          },
          grid: {
            left: '10px',
            right: '20px',
            top: '40px',
            bottom: '10px'
          },
          legend: {
            show: false
          },
          xAxis: {
            data: list
          },
          series: [{
            data: this.cpu.echartOption.series.data
          }]
        };
        this.memoryChangeData = {
          title: {
            left: '10px',
            top: '10px',
            text: '存储资源',
            textStyle: {
              color: '#333',
              fontSize: 14
            }
          },
          grid: {
            left: '10px',
            right: '20px',
            top: '40px',
            bottom: '10px'
          },
          legend: {
            show: false
          },
          xAxis: {
            data: list
          },
          series: [{
            data: this.memory.echartOption.series.data
          }]
        };
        break;
      default: ;
    }
  }

  ngAfterViewInit() {
    if (this.ping.echartsIntance && this.cpu.echartsIntance && this.memory.echartsIntance) {
      setTimeout(() => {
        this.ping.echartsIntance.resize();
        this.cpu.echartsIntance.resize();
        this.memory.echartsIntance.resize();
      }, 500);
    }
    if (this.pie.echartsIntance) {
      setTimeout(() => {
        this.pie.echartsIntance.resize();
      }, 500);
    }
  }

  beforeClose(): void { }

  beforeLeave(): boolean | Promise<boolean> {
    return new Promise(resolve => {
      resolve(true);
    });
  }

  getDate(date) {
    if (date == null) {
      return '-';
    }
    let dateObject = new Date(date);

    return this.esCommonService.getFormatDate(dateObject, 'yyyy-MM-dd hh:mm:ss')
  }

  getStatus() {
    return this.esCommonService.getStatus(this.data.data.status);
  }

  onChartInit(ec, target) {
    target.echartsIntance = ec;
  }

  switchTab(key) {
    this.currentTab = key;
    let str = this.data.data[key].replace(/G/g, '');
    let v = str.split('/');
    let numerator = v[0].split('(')[1];
    let denominator = v[1].split(')')[0];
    let formatter = key === 'disk' ? '{b}： {c}G ({d}%)' : '{b}： {c} ({d}%)';
    this.pieChangeData = {
      title: {
        text: ' ' + (100 * numerator / denominator).toFixed(0) + '%'
      },
      tooltip: {
        formatter: formatter
      },
      color: [this.legend[key].color, '#e6e6e6'],
      series: [{
        data: [
          { value: numerator, name: this.legend[key].name },
          { value: denominator - numerator, name: '未使用' }
        ]
      }]
    };
  }

  paginationChange() {
    this.loadData({
      search: '',
      pageNo: this.nowPage,
      pageSize: this.pageSize,
    });
  }

  loadData(data) {
    let d = this.cloudMachineService.queryMachine(data);
    this.tenantCloudDatas = d.data;
    this.totalCount = d.totalCount;
    this.nowPage = 1;
  }

  sortEvent(event) {
    this.loadData({
      search: '',
      pageNo: 1,
      pageSize: this.pageSize,
      sort: event
    });
  }

  isOver(data) {
    if (data == null) {
      return false;
    }

    let ds = data.split('%');
    if (ds && ds.length > 0) {
      if (ds[0] >= 80) {
        return true;
      }
    } else {
      return false;
    }
  }
}
